package com.millstein.realtime.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.millstein.realtime.app.base.BaseAppV1;
import com.millstein.realtime.bean.TradeOrderBean;
import com.millstein.realtime.bean.TradePaymentWindowBean;
import com.millstein.realtime.common.Constants;
import com.millstein.realtime.util.CommonUtil;
import com.millstein.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Dws_08_TradeOrderWindow extends BaseAppV1 {

    public static void main(String[] args) {
        new Dws_08_TradeOrderWindow().init(
                8008,
                3,
                "Dws_08_TradeOrderWindow",
                Constants.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }

    /**
     * 具体数据处理的逻辑，由子类编写
     *
     * @param env          执行环境对象
     * @param streamSource 待处理的数据流
     */
    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> streamSource) {
        // 1.过滤出当天独立下单的记录和新用户的下单记录
        SingleOutputStreamOperator<TradeOrderBean> orderStream = filterOrder(streamSource);
        // 2.开窗聚合
        SingleOutputStreamOperator<TradeOrderBean> resultStream = windowAndAgg(orderStream);
        // 3.将结果写入doris
        writeToDoris(resultStream);
    }

    private SingleOutputStreamOperator<TradeOrderBean> filterOrder(
            DataStreamSource<String> streamSource
    ) {
        return streamSource
                .map(new MapFunction<String, JSONObject>() {
                    @Override
                    public JSONObject map(String value) throws Exception {
                        return JSONObject.parseObject(value);
                    }
                })
                .keyBy(item -> item.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, TradeOrderBean>() {
                    ValueState<String> lastOrderDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        lastOrderDateState = getRuntimeContext().getState(
                                new ValueStateDescriptor<String>("last-order-date", String.class)
                        );
                    }

                    @Override
                    public void processElement(JSONObject value,
                                               Context ctx,
                                               Collector<TradeOrderBean> out
                    ) throws Exception {
                        Long ts = value.getLong("ts");
                        String today = CommonUtil.formatDate(ts);
                        if (!today.equals(lastOrderDateState.value())) {
                            out.collect(
                                    TradeOrderBean.builder()
                                            .orderUniqueUserCount(1L)
                                            .orderNewUserCount(0L)
                                            .ts(ts * 1000)
                                            .build()
                            );
                            if (lastOrderDateState.value() == null) {
                                out.collect(
                                        TradeOrderBean.builder()
                                                .orderUniqueUserCount(0L)
                                                .orderNewUserCount(1L)
                                                .ts(ts * 1000)
                                                .build()
                                );
                            }
                            lastOrderDateState.update(today);
                        }
                    }
                });
    }

    private SingleOutputStreamOperator<TradeOrderBean> windowAndAgg(
            SingleOutputStreamOperator<TradeOrderBean> orderStream
    ) {
        return orderStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<TradeOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner(new SerializableTimestampAssigner<TradeOrderBean>() {
                                    @Override
                                    public long extractTimestamp(TradeOrderBean element, long recordTimestamp) {
                                        return element.getTs();
                                    }
                                })
                )
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<TradeOrderBean>() {
                            @Override
                            public TradeOrderBean reduce(TradeOrderBean value1,
                                                         TradeOrderBean value2
                            ) throws Exception {
                                value1.setOrderUniqueUserCount(
                                        value1.getOrderUniqueUserCount() + value2.getOrderUniqueUserCount()
                                );
                                value1.setOrderNewUserCount(
                                        value1.getOrderNewUserCount() + value2.getOrderNewUserCount()
                                );
                                return value1;
                            }
                        },
                        new ProcessAllWindowFunction<TradeOrderBean, TradeOrderBean, TimeWindow>() {
                            @Override
                            public void process(Context context,
                                                Iterable<TradeOrderBean> elements,
                                                Collector<TradeOrderBean> out
                            ) throws Exception {
                                TradeOrderBean bean = elements.iterator().next();
                                String startTime = CommonUtil.formatTime(context.window().getStart());
                                String endTime = CommonUtil.formatTime(context.window().getEnd());
                                String curDate = startTime.substring(0, 10);
                                bean.setStt(startTime);
                                bean.setEdt(endTime);
                                bean.setCurDate(curDate);
                                out.collect(bean);
                            }
                        }
                );
    }

    private void writeToDoris(SingleOutputStreamOperator<TradeOrderBean> resultStream) {
        resultStream
                .map(item -> {
                    SerializeConfig config = new SerializeConfig();
                    config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
                    return JSONObject.toJSONString(item, config);
                })
                .addSink(FlinkSinkUtil.getDorisSink("gmall.dws_trade_order_window"));
    }
}
